package net.anzix.jimposition.transformations;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.swing.JPanel;
import net.anzix.jimposition.BasicTransformation;

public class ImpositionFilter extends BasicTransformation {

    int booklet = 16;

    private JPanel panel = new NoSettingsPanel();

    public byte[] alter(byte[] input) {
        try {
            PdfReader inputReader = new PdfReader(input);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            Rectangle pageSize = inputReader.getPageSize(1);
            Document document = new Document(pageSize);
            PdfWriter writer = PdfWriter.getInstance(document, outputStream);
            document.open();
            int pagenum = 1;
            int maxPageNumOriginal = inputReader.getNumberOfPages();
            int maxPageNum = getNumberOfPages(maxPageNumOriginal);
            PdfContentByte cb = writer.getDirectContent();
            for (int page = 1; page <= maxPageNum; page++) {
                document.newPage();
                if (getPageNo(page) <= maxPageNumOriginal) {
                    cb.addTemplate(writer.getImportedPage(inputReader, getPageNo(page)), 1.0f, 0f, 0f, 1.0f, 0f, 0f);
                }
                cb.stroke();
            }
            document.close();
            return outputStream.toByteArray();
        } catch (DocumentException ex) {
            ex.printStackTrace();
            return null;
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }

    }

    private int getPageNo(int pageno) {
        int base = (pageno - 1) / booklet;
        int k = (pageno - 1 - base * booklet) / 4;
        if (pageno % 4 == 1) {
            return base * booklet + booklet - 2 * k;
        }
        if (pageno % 4 == 2) {
            return base * booklet + 1 + 2 * k;
        }
        if (pageno % 4 == 3) {
            return base * booklet + 2 + 2 * k;
        }
        if (pageno % 4 == 0) {
            return base * booklet + (booklet - 1) - 2 * k;
        }
        return 0;

    }

    private int getNumberOfPages(int page) {
        return (int) java.lang.Math.ceil((double) page / booklet) * booklet;
    }

    public String toString() {
        return "Imposition page order";
    }

    public void setPanelSettings() {
    }

    public void getPanelSettings() {
    }

    public JPanel getPanel() {
        return panel;
    }
}
